<template>
  <view>
    <view class="content">
      <view class="row">
        <view class="nominal">收件人</view>
        <view class="input">
          <input placeholder="请输入收件人姓名" type="text" v-model="name" />
        </view>
      </view>
      <view class="row">
        <view class="nominal">电话号码</view>
        <view class="input">
          <input placeholder="请输入收件人电话号码" type="text" v-model="tel" />
        </view>
      </view>
      <view class="row">
        <view class="nominal">所在地区</view>
        <view class="input" @tap="chooseCity">{{region.label}}</view>
      </view> 
      <view class="row">
        <view class="nominal">详细地址</view>
        <view class="input">
          <textarea v-model="detailed" auto-height="true" placeholder="输入详细地址"></textarea>
        </view>
      </view>
      <view class="row">
        <view class="nominal">设置默认地址</view>
        <view class="input switch">
          <switch color="#354E44" :checked="isDefault" @change="isDefaultChange" />
        </view>
      </view>
      <view class="row" v-if="editType=='edit'" @tap="del">
        <view class="del">删除收货地址</view>
      </view>
    </view>
    <view class="save" @tap="save">
      <view class="btn">保存地址</view>
    </view>
    <mpvue-city-picker
      :themeColor="themeColor"
      ref="mpvueCityPicker"
      :pickerValueDefault="cityPickerValue"
      @onCancel="onCancel"
      @onConfirm="onConfirm"
    ></mpvue-city-picker>
  </view>
</template>

<script>
import mpvueCityPicker from "@/components/mpvue-citypicker/mpvueCityPicker.vue";
import addressApi from "@/api/mine/address.js";
export default {
  name: "AddressEdit",
  components: {
    mpvueCityPicker
  },
  data() {
    return {
      editType: "edit",
      id: "",
      name: "",
      tel: "",
      detailed: "", //详细地址
      isDefault: false, //是否默认
      cityPickerValue: [0,0,0], //地区代表字码
      themeColor: "#007AFF",
      region: { label: "请点击选择地址", value: [], cityCode: "" },   //区域
      address: {}
    };
  },
  methods: {
    onCancel(e) {
      console.log(e);
    },
    chooseCity() {
      this.$refs.mpvueCityPicker.show();
    },
    onConfirm(e) {
      this.region = e;
      this.cityPickerValue = e.value;
    },
    isDefaultChange(e) {
      this.isDefault = e.detail.value;  //设置默认地址
    },
    del() {
      uni.showModal({
        title: "删除提示",
        content: "你将删除这个收货地址",
        success: res => {
          if (res.confirm) {  //confirm(为 true 时，表示用户点击了确定按钮)
            uni.setStorage({
              key: "delAddress",
              data: { id: this.id },
              success() {
                uni.navigateBack();
              }
            });
          } else if (res.cancel) { //cancel(为 true 时，表示用户点击了取消)
            console.log("用户点击取消");
          }
        }
      });
    },
    save() {
      let data = {
        name: this.name,
        head: this.name.substr(0, 1),  //地址第一个图标显示用户名字的首字母 //substr()方法可在字符串中抽取从start下标开始的指定数目的字符。stringObject.substr(start,length)
        tel: this.tel,
        address: { region: this.region, detailed: this.detailed },
        isDefault: this.isDefault
      };
      if (this.editType == "edit") {
        data.id = this.id;
      }
      if (!data.name) {
        uni.showToast({ title: "请输入收件人姓名", icon: "none" });
        return;
      }
      if (!data.tel) {
        uni.showToast({ title: "请输入收件人电话号码", icon: "none" });
        return;
      }
      if (!data.address.detailed) {
        uni.showToast({ title: "请输入收件人详细地址", icon: "none" });
        return;
      }
      if (data.address.region.value.length == 0) {
        uni.showToast({ title: "请选择收件地址", icon: "none" });
        return;
      }
      uni.showLoading({
        title: "正在提交"
      });
      // 构建可提交内容  把cityCode和value拼接一块
      var cityCodeArr = [];
      cityCodeArr[0] = this.region.cityCode;
      for (var i = 0; i < this.region.value.length; i++) {
        cityCodeArr.push(this.region.value[i]); //push() 方法可向数组的末尾添加一个或多个元素，并返回新的长度。
      }
	  var postData = {
		  userId: this.$store.getters.userId,
          tag: data.head,
          name: data.name,
          tel: data.tel,
          cityCode: cityCodeArr.join(), //join() 方法用于把数组中的所有元素放入一个字符串。元素是通过指定的分隔符进行分隔（逗号）。
		  cityStr: this.region.label, //详细地址
		  cityBak: this.detailed, //备注地址
		  isUse: this.isDefault?1:0 //是否默认0否,1是 字符串类型
        }
	  var api = null;
	  if(this.id){
		  api = addressApi.addressUpdate;  //编辑的修改地址
		  postData.id = this.id;
	  }else{
		  api = addressApi.addressSave;  //新增地址
	  }
      api(postData)
        .then(res => {
			if(res.code == 'S'){
				uni.showToast({
					title:'保存成功!',
					duration:1000
				})
				uni.navigateTo({
					url:'../index'
				})
			}else{
				uni.showToast({
					title: '保存失败!',
					duration:1000
				})
			}
		});
    }
  },
  onLoad(e) {
    //获取传递过来的参数
    this.editType = e.type;
    if (e.type == "edit") {
		
		var addressObj = uni.getStorageSync("address"); //编辑地址时设置的key值
		var cityArr = addressObj.address.region.value;
		console.log(cityArr);
		cityArr = cityArr.map(item=>(item-0)); //对cityArr数组进行转换,返回的是字符串=》数字   //map() 方法创建一个新数组，其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
		this.id = addressObj.id;
		this.name = addressObj.name;
		this.tel = addressObj.tel;
		this.detailed = addressObj.address.region.detailed;
		this.isDefault = addressObj.isDefault;
		this.cityPickerValue = cityArr;
		this.region = addressObj.address.region;
    }
  },
  onBackPress() {
    if (this.$refs.mpvueCityPicker.showPicker) {
      this.$refs.mpvueCityPicker.pickerCancel();
      return true;
    }
  },
  onUnload() {
    if (this.$refs.mpvueCityPicker.showPicker) {
      this.$refs.mpvueCityPicker.pickerCancel();
    }
  }
};
</script>
<style lang="scss">
.save {
  view {
    display: flex;
  }
  position: fixed;
  bottom: 0;
  width: 100%;
  height: 120upx;
  display: flex;
  justify-content: center;
  align-items: center;
  .btn {
    box-shadow: 0upx 5upx 10upx rgba(0, 0, 0, 0.4);
    width: 70%;
    height: 80upx;
    border-radius: 80upx;
    background-color: #354E44;
    color: #fff;
    justify-content: center;
    align-items: center;
    .icon {
      height: 80upx;
      color: #fff;
      font-size: 30upx;
      justify-content: center;
      align-items: center;
    }
    font-size: 30upx;
  }
}
.content {
  display: flex;
  flex-wrap: wrap;
  view {
    display: flex;
  }
  .row {
    width: 94%;

    margin: 0 3%;
    border-top: solid 1upx #eee;
    .nominal {
      width: 30%;
      height: 120upx;
      font-weight: 200;
      font-size: 30upx;
      align-items: center;
    }
    .input {
      width: 70%;
      padding: 20upx 0;
      align-items: center;
      font-size: 30upx;
      &.switch {
        justify-content: flex-end;
      }
      .textarea {
        margin: 20upx 0;
        min-height: 120upx;
      }
    }
    .del {
      width: 100%;
      height: 100upx;
      justify-content: center;
      align-items: center;
      font-size: 36upx;
      color: #354E44;
      background-color: rgba(255, 0, 0, 0.05);
      border-bottom: solid 1upx #eee;
    }
  }
}
</style>
